<?php
// public/users.php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/db.php';
require_login();

$user = current_user();
if ($user['role'] !== 'public') {
    header('Location: dashboard.php');
    exit;
}

$msg = null;
$type = 'success';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_user'])) {
    $name = trim($_POST['name']);
    $email = trim($_POST['email']);
    try {
        $stmt = $pdo->prepare("
            INSERT INTO department (department, college_office)
            VALUES (?, ?)
        ");
        $stmt->execute([$name, $email]);

        header("Location: unit.php?msg=Unit+added+successfully&type=success");
        exit;
    } catch (PDOException $e) {
        header("Location: unit.php?msg=Error:+COllege+already+exists&type=danger");
        exit;
    }
}

// --- Update user ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_user'])) {
    $id = $_POST['id'];
    $name = trim($_POST['name']);
    $email = trim($_POST['email']);

    try {
        if (!empty($_POST['email'])) {
            
            $stmt = $pdo->prepare("UPDATE department SET department=?, college_office=? WHERE id=?");
            $stmt->execute([$name, $email, $id]);
        } else {
            $stmt = $pdo->prepare("UPDATE department SET department=?, college_office=? WHERE id=?");
            $stmt->execute([$name, $email, $id]);
        }

        header("Location: unit.php?msg=Unit+updated+successfully&type=success");
        exit;
    } catch (PDOException $e) {
        header("Location: unit.php?msg=Error:+Could+not+update&type=danger");
        exit;
    }
}

// --- Delete user ---
if (isset($_GET['delete'])) {
    $id = $_GET['delete'];
    try {
        $stmt = $pdo->prepare("DELETE FROM department WHERE id=?");
        $stmt->execute([$id]);
        header("Location: unit.php?msg=Unit+deleted+successfully&type=success");
        exit;
    } catch (PDOException $e) {
        header("Location: unit.php?msg=Error:+Could+not+delete&type=danger");
        exit;
    }
}

// --- Fetch all accounts ---
$stmt = $pdo->query("SELECT id, department, college_office FROM department ORDER BY id DESC");
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

$title = "Users | JO & COS RMS";
include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>

<section class="content-header">
  <div class="container-fluid">
    <h1>Users <small class="text-muted">Manage Accounts</small></h1>
  </div>
</section>

<section class="content">
  <div class="container-fluid">

    <?php if (isset($_GET['msg'])): ?>
      <div class="alert alert-<?= htmlspecialchars($_GET['type'] ?? 'info') ?> alert-dismissible fade show" role="alert">
        <?= htmlspecialchars($_GET['msg']) ?>
        <button type="button" class="close" data-dismiss="alert">&times;</button>
      </div>
    <?php endif; ?>

    <div class="card">
       <div class="card-header">
        <a class="btn btn-primary" href="users.php">
          <i class="fas fa-user"></i> User
        </a>
		 <a class="btn btn-primary" href="unit.php">
          <i class="fas fa-user"></i> Unit
        </a>
		 <a class="btn btn-primary" href="jobtitle.php">
          <i class="fas fa-user"></i> Jobtitle
        </a>
      </div>
      <div class="card-body table-responsive">
	  <button class="btn btn-primary" data-toggle="modal" data-target="#addUserModal">
          <i class="fas fa-plus"></i> Add Unit
        </button>
        <table id="usersTable" class="table table-bordered table-striped nowrap" style="width:100%">
          <thead>
            <tr>
              <th>ID</th>
              <th>Department</th>
              <th>College Office</th>
              <th>Action</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($users as $u): ?>
            <tr>
              <td><?= $u['id'] ?></td>
              <td><?= htmlspecialchars($u['department']) ?></td>
              <td><?= htmlspecialchars($u['college_office']) ?></td>
			  
              <td>
                <button class="btn btn-sm btn-warning mb-1" data-toggle="modal" data-target="#editUserModal<?= $u['id'] ?>">
                  <i class="fas fa-edit"></i>
                </button>
                <a href="?delete=<?= $u['id'] ?>" class="btn btn-sm btn-danger mb-1" onclick="return confirm('Delete this user?')">
                  <i class="fas fa-trash"></i>
                </a>
              </td>
            </tr>
            <div class="modal fade" id="editUserModal<?= $u['id'] ?>" tabindex="-1">
              <div class="modal-dialog modal-md">
                <div class="modal-content">
                  <form method="post">
                    <input type="hidden" name="id" value="<?= $u['id'] ?>">
                    <div class="modal-header">
                      <h5 class="modal-title">Edit Unit</h5>
                      <button type="button" class="close" data-dismiss="modal">&times;</button>
                    </div>
                    <div class="modal-body">
                      <div class="form-group"><label>Department</label>
                        <input type="text" name="name" value="<?= htmlspecialchars($u['department']) ?>" class="form-control" required>
                      </div>
                      <div class="form-group"><label>College Office</label>
                        <input type="text" name="email" value="<?= htmlspecialchars($u['college_office']) ?>" class="form-control" required>
                      </div>
                     
                    </div>
                    <div class="modal-footer">
                      <button type="submit" name="edit_user" class="btn btn-primary">Save</button>
                      <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    </div>
                  </form>
                </div>
              </div>
            </div>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</section>

<!-- Add User Modal -->
<div class="modal fade" id="addUserModal" tabindex="-1">
  <div class="modal-dialog modal-md">
    <div class="modal-content">
      <form method="post">
        <div class="modal-header">
          <h5 class="modal-title">Add Unit</h5>
          <button type="button" class="close" data-dismiss="modal">&times;</button>
        </div>
        <div class="modal-body">
          <div class="form-group"><label>Department</label><input type="text" name="name" class="form-control" required></div>
          <div class="form-group"><label>College Office</label><input type="text" name="email" class="form-control" required></div>
   
        </div>
        <div class="modal-footer">
          <button type="submit" name="add_user" class="btn btn-primary">Save</button>
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
        </div>
      </form>
    </div>
  </div>
</div>

<?php include __DIR__ . '/../includes/footer.php'; ?>

<!-- DataTables -->
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap4.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap4.min.css"/>
<link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.5.0/css/responsive.bootstrap4.min.css"/>

<script>
$(function () {
  $('#usersTable').DataTable({
    responsive: true,
    autoWidth: false
  });
});
</script>
